<?php

// +----------------------------------------------------------------------
// | 分类控制器
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\app\admin;

use yicmf\builder\Edit;
use yicmf\builder\Table;
use think\facade\Url;
use app\controller\admin\Common;
use app\model\app\ExchangeCouponOrder as ExchangeCouponOrderModel;
use app\event\app\ThirdRecharge as ThirdRechargeEvent;


class ExchangeCouponOrder extends Common
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function _filter()
    {
    }

    public function index()
    {

        $statusOptions = [
            [
                'id' => 1,
                'value' => '信用卡'
            ],
            [
                'id' => 2,
                'value' => '贷款'
            ],
            [
                'id' => 3,
                'value' => '租机'
            ]
        ];
        //读取规则列表
        $map = $this->_search($this->dbname);
        //            //显示页面
        $builder = new Table();
        $builder->model(ExchangeCouponOrderModel::class)
            ->where($map)
            ->order('id DESC')
            ->setSearchPostUrl('', '')
            ->searchTextLike('template', '充值号码：')
            ->searchUser('下单用户')
//            ->searchSelect('type','产品类型',$statusOptions)
//            ->searchBool('is_new','新品')
//            ->searchBool('is_hot','推荐')
            ->keyId()
            ->keyText('name', '卡券名称')
            ->keyText('sn', '平台单号')
            ->keyText('order_id', '渠道单号')
            ->keyText('template', '充值号')

            ->keyText('remark', '反馈信息')
            ->keyText('voucher','凭证')
            ->keyText('charge_kami', '卡密')
//                ->keyText('label1', '标签1')
//                ->keyText('label2', '标签2')
            ->keyText('msg', '消息')
            ->keyUser('user_id', '推广用户')
            ->keyUpdateTime()
            ->keyTime('pay_time', '支付时间')
//                ->keyText('applyMsg','简介')
//            ->keyText('sort', '排序')
            ->keyMap('status', '状态', ['创建', '等待支付', '等待发货', '已发货', '交易成功', '交易取消', '处理中','全额退费'])//-1取消， 0充值中， 1充值成功 ，2充值失败，3部分成功（-1,2做失败处理；1做成功处理；3做部分成功处理）
            /**
             * status==1    等待支付，下一时刻会变成2
             * status==2    等待发货，等待处理
             * status==3    已发货，物流派送中
             * status==4    交易成功，订单完成，虚拟充值商品订单成功为该状态
             * status==5    交易取消，订单失败，虚拟充值商品订单失败为该状态
             * status==6    处理中，正在处理
             */
//            ->actionForbid('cancel?id={$id}', '撤单', [3])
//            ->actionUpdate('restart?id={$id}', '重提', [1,5])
            ->actionUpdate('back?id={$id}', '退费', [5]);
        return $builder->fetch();
    }

    public function restart()
    {
        if ($this->request->isPost()) { //提交表单

            $event = new ThirdRechargeEvent();
            $data = $event->restart($this->request->param(), $this->user);
            return $this->_returnAuto($data);
        } else {
            /* 获取分类信息 */
            $id = $this->request->get('id');
            $isEdit = $id ? true : false;
            if ($isEdit) {
                $data = ExchangeCouponOrderModel::where('id', $id)->find();
                if (!$data) {
                    $this->_returnError('分类不存在或者已经删除');
                }
            } else {
                $data['type'] = 1;
            }
            $builder = new Edit();
            $builder->title('重提充值')
                ->keyLabel('channel_name', '渠道信息')
                ->keyTextInline('template', '充值号码')
                ->keyTextInline('area', '省')
                ->keyTextInline('city', '市')
                ->keyLabel('remark', '反馈信息')
                ->data($data)
                ->buttonSubmit('', '保存');
            //                    ->buttonClose();
            return $builder->fetch();
        }
    }

    public function cancel()
    {
        $event = new ThirdRechargeEvent();
        $data = $event->cancel($this->request->param(), $this->user);
        return $this->_returnAuto($data);
    }

    public function back()
    {
        if ($this->request->isPost()) { //提交表单

            $event = new ThirdRechargeEvent();
            $data = $event->back($this->request->param(), $this->user);
            return $this->_returnAuto($data);
        } else {
            /* 获取分类信息 */
            $id = $this->request->get('id');
            $isEdit = $id ? true : false;
            if ($isEdit) {
                $data = ExchangeCouponOrderModel::where('id', $id)->where('status', 'in', [1,2, 5, 6])->find();
                if (!$data) {
                    throw new Exception('订单状态不支持退款');
                }
            } else {
                throw new Exception('请选择退款记录');
            }
            $builder = new Edit();
            $builder->title('退费申请')
                ->keyLabel('channel_name', '渠道信息')
                ->keyLabel('template', '充值号码')
                ->keyLabel('area', '地区')
                ->keyLabel('remark', '反馈信息')
                ->keyLabel('pay_time', '支付时间')
                ->keyRadio('type', '退款形式', ['全额退', '扣除手续费', '指定金额'])
                ->keyTextInline('out_request_no', '次数', '部分退款需要填写', 1)
                ->keyTextInline('reason', '理由', '', $data['remark'])
                ->keyDecimal('amount', '退款金额', '实际退回金额')
                ->setTrigger('type', 0, '')
                ->setTrigger('type', 1, 'out_request_no')
                ->setTrigger('type', 2, 'amount,out_request_no')
                ->data($data)
                ->buttonSubmit('', '提交');
            //                    ->buttonClose();
            return $builder->fetch();
        }
    }

    /**
     * 编辑分类
     * @access protected
     * @author 微尘 <yicmf@qq.com>
     */
    public function update()
    {
        if ($this->request->isPost()) { //提交表单
            $check = $this->validate($this->request->param(), \app\validate\app\ExchangeCouponOrder::class);
            if ($check !== true) {

                $this->_returnError($check);
            } else {
                if ($this->request->param('id')) {

                    $data = ExchangeCouponOrderModel::where('id', $this->request->param('id'))->find();
                    $info = $this->request->except(['id']);
                    $data->save($info);
                    if ($task = TaskModel::where('type', 6)->where('relation_id', $data['id'])->find()) {
                        // 更新
                        $task['title'] = $data['bankName'];
                        $task['commission'] = $data['commission'];
                        $task['introduce'] = $data['shortIntroduce'];
                        $task->save();
                    } else {
                        $task['name'] = '信用产品';
                        $task['title'] = $data['bankName'];
                        $task['commission'] = $data['commission'];
                        $task['is_top'] = $data['is_hot'];
                        $task['introduce'] = $data['shortIntroduce'];
                        $task['relation_id'] = $data['id'];
                        $task['user_id'] = $this->user['id'];
                        $task['type'] = 6;
                        $re = TaskModel::create($task);
                    }
                    $this->_returnSuccess('更新成功');
                } else {
                    $re = ExchangeCouponOrderModel::create($this->request->param());
                    if ($re) {
                        // 新增任务
                        $task['name'] = '信用产品';
                        $task['title'] = $re['bankName'];
                        $task['introduce'] = $re['shortIntroduce'];
                        $task['commission'] = $re['commission'];
                        $task['is_top'] = $re['is_hot'];
                        $task['relation_id'] = $re['id'];
                        $task['user_id'] = $this->user['id'];
                        $task['type'] = 6;
                        $re = TaskModel::create($task);
                        if ($re) {
                            $this->_returnSuccess('新增成功');
                        } else {
                            $this->_returnError('新增异常');
                        }
                    } else {

                        $this->_returnError('新增异常');
                    }
                }
            }

        } else {
            /* 获取分类信息 */
            $id = $this->request->get('id');
            $isEdit = $id ? true : false;
            if ($isEdit) {
                $data = ExchangeCouponOrderModel::where('id', $id)->find();
                if (!$data) {
                    $this->_returnError('分类不存在或者已经删除');
                }
            } else {
                $data['type'] = 1;
            }
            $builder = new Edit();
            $builder->title('编辑')
                ->keyText('bankName', '产品名称')
                ->keyText('product_url', '渠道链接')
                ->keyImage('logo', 'logo', '')
                ->keyImage('poster_image', '推广海报', '');
//                ->keyImageModel('poster_image_id', '推广海报', '');
            if (!$isEdit) {
                $builder->keyRadio('type', '产品类型', [1 => '信用卡', 2 => '贷款', 3 => '租机'], '', 1);
            }

            $builder->keyRadio('commission_type', '佣金结算方式', ['0' => '佣金结算', '1' => '百分比结算', '2' => '阶段结算'], '', 0)
                ->keyRadio('settlementType', '结算方式', ['1' => '自动结算', '2' => '手动结算'], '', 1)
                ->keyText('commission_remark', '阶段结算备注')
                ->keyText('label1', '标签1')
                ->keyText('label2', '标签2')
                ->keyDecimal('commission', '佣金')
                ->keySort()
                ->keyNumber('virtualNum', '虚拟下卡数量')
                ->keyTextArea('shortIntroduce', '产品简介')
                ->keyEditor('settlementRules', '结算规则')
                ->keyEditor('applyMsg', '申请条件');
            if ($isEdit) {
                if ($data['type'] == 1) {
                    $builder->keyEditor('interestMsg', '权益介绍');
                } else {
                    $builder->keyEditor('interestMsg', '注意事项');
                }
            } else {
                $builder->keyEditor('interestMsg', '权益介绍[注意事项]');
            }
            $builder->keyBool('is_new', '新品')
                ->keyBool('is_hot', '推荐')
                ->keyBool('status', '是否上架')
                ->data($data)
                ->buttonSubmit('', '保存');
            //                    ->buttonClose();
            return $builder->fetch();
        }
    }
}